package com.coldchain.admin.config.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.coldchain.admin.config.entity.Map;
import com.coldchain.admin.config.service.IMapService;
import com.coldchain.admin.search.MapSearch;
import com.coldchain.authclient.annotation.CheckUserToken;
import com.coldchain.common.exception.base.BusinessException;
import com.coldchain.common.msg.ObjectRestResponse;
import com.fangliai.core.context.BaseContextHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author fangliai
 * @since 2018-09-14
 */
@RestController
@CheckUserToken
@RequestMapping("/map")
public class MapController {
    private static final Logger log= LoggerFactory.getLogger(MapController.class);
    @Autowired
    private IMapService mapService;

    /**
     * 高及查询
     * @param {查询对象}  search
     * @return
     */
    @GetMapping("/search")
    public ObjectRestResponse<List<Map>> search(MapSearch search){

        return  new ObjectRestResponse<>().data(mapService.search(search));
    }

    @PostMapping("/edit")
    public Object edit(Map map){
        try {
            QueryWrapper wrapper= new QueryWrapper<>().eq("appKey",map.getAppKey());
            int size=  mapService.count(wrapper);
            if(size<=0){
                map.setCreateBy(BaseContextHandler.getUsername());
                map.setCreateTime(new Date().getTime());
            }
            mapService.saveOrUpdate(map);
            return  new ObjectRestResponse<>().succeed();
        }catch (Exception e){
            log.error(e.getMessage());
            throw  new BusinessException("服务器异常");
        }
    }

    @PostMapping("/del/{id}")
    public  Object del(@PathVariable("id") Integer id){
        mapService.removeById(id);
        return  new ObjectRestResponse<>().succeed();
    }
}
